package ucadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryAppConfigLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryAppConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryAppConfigLogic {
	return &QueryAppConfigLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询app配置
func (l *QueryAppConfigLogic) QueryAppConfig(in *pb.QueryAppConfigReq) (*pb.QueryAppConfigResp, error) {
	defer utils.RecoverPanic()

	var list []*usercenter.AppConfig
	var err error
	list, err = l.svcCtx.AppConfigModel.Find(l.ctx, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var resp pb.QueryAppConfigResp
	resp.List = make([]*pb.AppConfig, 0)
	if len(list) <= 0 {
		return &resp, nil
	}
	if in.PageNo <= 1 {
		resp.Total, err = l.svcCtx.AppConfigModel.Count(l.ctx)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		var vl pb.AppConfig
		vl.AppVersion = list[i].AppVersion
		vl.CheckState = list[i].CheckState
		vl.CreateTime = list[i].CreateTime.Format(dbkey.DateTimeCNFormat)
		vl.UpdateTime = list[i].UpdateTime.Format(dbkey.DateTimeCNFormat)
		vl.TextState = list[i].TextState
		vl.PayState = list[i].PayState
		vl.RankState = list[i].RankState
		vl.Name = list[i].Name
		vl.PkgName = list[i].PkgName
		vl.Remark = list[i].Remark
		resp.List = append(resp.List, &vl)
	}

	return &resp, nil
}
